package com.hqu.environment.utils;

import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Description: 全局异常捕获类，捕获全局抛出的指定Exception异常，包括ApiException业务异常和BindException绑定vo异常
 *                  并统一封装以@responsebody方式传出，可随时返回，不需要一层层的try...catch
 * @Author: 邓勇嘉
 * @Date:2018/11/19 18:12
 * */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获ApiException业务异常,并直接返回错误结果
     *
     * @param e ApiException业务异常
     * @return Result 错误结果
     */

    @ExceptionHandler(value = ApiException.class)
    public Result domainExceptionHandler(ApiException e){
        //抛出错误信息
        return Result.fail(e.getErrno(), e.getErrmsg());
    }


    /**
     * 捕获BindException vo绑定异常,并直接返回错误结果
     *
     * @param e BindException vo绑定异常
     * @return Result 错误结果
     */
    @ExceptionHandler(value = BindException.class)
    public Result bindException(BindException e) {
        //获取绑定异常解雇哟
        BindingResult bindingResult = e.getBindingResult();

        String errorMessage = "";
        //遍历异常信息并赋值
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage += fieldError.getDefaultMessage() + ";";
        }
        //抛出错误异常
        return Result.fail(11000, errorMessage);
    }

}
